<template>
  <transition name="message-fade">
    <div
      class="r-message"
      v-if="visible"
      :style="computedStyle"
      :class="computedClass"
    >
      <div class="r-message__content">
        <span v-if="type">
          <r-icon :name=getIconName></r-icon>
        </span>
        {{message}}
        <span class="close-btn" @click="closeMessage">
          <w-icon name="yiliao_danao"></w-icon>
        </span>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: "w-message",

  data() {
    return {
      visible: false,
      verticalTop: 0,
      baseOffset: 16,
    };
  },
  props: {
    message: {
      type: [Number, String],
    },
    duration: {
      type: [Number],
      default: 3000,
    },
    autoClose: {
      type: Boolean,
      default: false,
    },
    position: {
      type: [Number, String],
      default: "left",
    },
    type: {
      type: [Number, String],
    },
  },
  computed: {
    computedStyle() {
      return {
        top: this.verticalTop + "px",
        ...(this.LR_POSTION && {
          [`${this.position}`]: this.baseOffset + "px",
        }),
        ...(this.CENTER_POSTION && {
          left: "50%",
          marginLeft: "-190px",
        }),
      };
    },
    computedClass() {
      return {
        [`r-message--${this.type}`]: this.type,
      };
    },
    getIconName(){
      const ICONS={
        success:'goul',
        error:'chahao',
        info:'info',
        warning:'warn'
      }
      return ICONS[this.type]
    },
    LR_POSTION() {
      return this.position === "left" || this.position === "right";
    },
    CENTER_POSTION() {
      return this.position === "center";
    },
  },
  mounted() {
    this.createElment();
    this.autoClose || this.starttimer();
  },
  methods: {
    createElment() {
      this.visible = true;
      document.body.appendChild(this.$el);
      console.log(this.visible);
    },
    closeMessage() {
      this.visible = false;
    },
    starttimer() {
      let timer = setTimeout(() => {
        this.visible = false;
      }, this.duration);
      this.$once("hook:beforeDestroy", () => {
        clearTimeout(timer);
        timer = null;
      });
    },
  },
  watch: {
    visible(newValue) {
      if (!this.visible) {
        this.$el.addEventListener("transitionend", () => {
          this.$destroy;
        });
        this.$emit("close", this.verticalTop);
      }
    },
  },
  beforeDestroy() {
    this.$el.parentNode.removeChild(this.$el);
  },
};
</script>

<style scoped>
@import "./message.css";
</style>